<template>
	<view>
		<view class="search-container-bar">
			<view class="search-title-box">
				<text>有需要时，搜索查询商城分类</text>
			</view>
			<uni-search-bar bgColor="#ffffff" ref="searchBar" style="flex:1;" radius="100" v-model="searchText"
				:focus="focus" clearButton="auto" cancelButton="always" @clear="clear" @confirm="confirm" @focus="onFocus"
				@cancel="cancel" />
				<view class="note-box">
					<text>{{currentSearchText}}</text>
				</view>
		</view>

		<view class="picker-box">
			<uni-data-picker class="picker-item" placeholder="请选择分类" popup-title="请选择分类"
				collection="tian-mall-categories" field="_id as value, name as text,sort" orderby="sort asc"
				:preload="true" :step-searh="true" :clear-icon="false" self-field="_id" parent-field="parent_id"
				@change="onchange" @nodeclick="onnodeclick">
			</uni-data-picker>
		</view>

		<!-- 搜索联想 -->
		<view class="search-associative" v-if="associativeShow">
			<uni-list>
				<uni-list-item v-for="(item,index) in associativeList" :key="index" :ellipsis="2" :title="item"
					@click="associativeClick(item)" show-extra-icon clickable
					:extra-icon="{size:22,color:iconColor,type:'info-filled'}" />
			</uni-list>
		</view>

		<view class="confirm-btn-box" v-if="showConfirmBtn">
			<button type="primary" size="mini" @click="confirmBack">确认分类并返回</button>
		</view>

	</view>
</template>

<script>
	/**
	 * 云端一体搜索模板
	 * @description uniCloud云端一体搜索模板，自带下拉候选、历史搜索、热搜。无需再开发服务器代码
	 */
	const searchLogDbName = 'opendb-search-log'; // 搜索记录数据库
	const mallCategoriesName = 'tian-mall-categories'; // 商品数据库
	const associativeSearchField = 'name'; // 联想时，搜索框值检索数据库字段名
	const associativeField = 'name,sort'; // 联想列表每一项携带的字段
	const localSearchListKey = '__local_search_history'; //	本地历史存储字段名

	// 数组去重
	const arrUnique = arr => {
		for (let i = arr.length - 1; i >= 0; i--) {
			const curIndex = arr.indexOf(arr[i]);
			const lastIndex = arr.lastIndexOf(arr[i])
			curIndex != lastIndex && arr.splice(lastIndex, 1)
		}
		return arr
	} // 节流
	// 防抖
	function debounce(fn, interval, isFirstAutoRun) {
		/**
		 * 
		 * @param {要执行的函数} fn 
		 * @param {在操作多长时间后可再执行，第一次立即执行} interval 
		 */
		var _self = fn;
		var timer = null;
		var first = true;

		if (isFirstAutoRun) {
			_self();
		}

		return function() {
			var args = arguments;
			var _me = this;
			if (first) {
				first = false;
				_self.apply(_me, args);
			}

			if (timer) {
				clearTimeout(timer)
				// return false;
			}

			timer = setTimeout(function() {
				clearTimeout(timer);
				timer = null;
				_self.apply(_me, args);
			}, interval || 200);
		}
	}

	// 处理搜索结果，将其变为节点的分类名称链
	/**
	 * @param {Object} data 对象 读取数据库返回的数组元素
	 * @param {Object} resData 返回 字符串
	 */
	// let ttData = [] //设置中间变量,用于储存处理数据的中间值
	function handleSeachResult(data, resData) {
		resData.push(data.name)
		if (data.children) {
			return handleSeachResult(data.children[0], resData)
		} else {
			return resData.join(' > ')
		}


	}
	export default {
		data() {
			return {
				mallCategoriesName: 'tian-mall-categories',
				currentSearchText:'',
				searchText: '',
				associativeList: [],
				iconColor: '#f37b1d',
				associativeList: [],
				focus: true, //	是否自动聚焦
				showConfirmBtn: false,
				categoriesData: null
			}
		},
		computed: {
			associativeShow() {
				return this.searchText && this.associativeList.length;
			}
		},
		watch: {
			searchText: debounce(function(value) {
				if (value) {
					this.mallCategoriesDb.field(associativeField).get({
						getTreePath: {
							"startWith": `${new RegExp(value, 'gi')}.test(name)`
						}
					}).then(res => {
						// console.log('接收数据',res.result.data);
						let resHandle = []
						for (var i = 0; i < res.result.data.length; i++) {
							resHandle.push(handleSeachResult(res.result.data[i], []))
							// resHandle=handleSeachResult(res.result.data[i])
						}
						// console.log('处理数据',resHandle);
						this.associativeList = resHandle;
					})
				} else {
					this.associativeList.length = 0;
				}
			}, 100)
		},
		onLoad(option) {
			if (option.name) {
				uni.setNavigationBarTitle({
					title: option.name
				})
			}

		},
		created() {
			this.db = uniCloud.database();
			// this.searchLogDb = this.db.collection(this.searchLogDbName);
			this.mallCategoriesDb = this.db.collection(this.mallCategoriesName);

			// #ifdef APP-PLUS
			uni.onKeyboardHeightChange((res) => {
				this.keyBoardPopup = res.height !== 0;
			})
			// #endif

			// this.searchText = getApp().globalData.searchText;
		},
		methods: {
			confirmBack() {
				uni.navigateBack({
					delta: 1
				});
			},
			associativeClick(item) {
				this.currentSearchText=item
				this.cancel()
				// console.log("associativeClick: ", item);
			},
			onFocus(){
				this.currentSearchText=''
			},
			clear(res) {
				// console.log("res: ", res);
			},
			confirm(res) {
				// 键盘确认
				this.search(res.value);
			},
			cancel(res) {
				uni.hideKeyboard();
				this.searchText = '';
				// this.loadList();
			},
			onchange(e) {
				// const value = e.detail.value
				this.categoriesData = e.detail.value
			},
			onnodeclick(node) {
				// console.log(node);
				if (node.isleaf) {
					this.showConfirmBtn = true
					this.getOpenerEventChannel().emit('conformCategory', this.categoriesData)
				} else {
					this.showConfirmBtn = false
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	$search-bar-height: 52px;

	.picker-box {
		width: 100;
		margin: 30rpx 20rpx;

		.picker-item {
			// padding: 20rpx;
			background-color: #fff;
		}
	}

	.search-title-box {
		margin-top: 30rpx;

		text {
			margin-left: 100rpx;
			color: #555;
			font-size: 28rpx;
		}
	}

	.search-associative {
		/* #ifndef APP-NVUE */
		overflow-y: auto;
		/* #endif */
		position: absolute;
		top: $search-bar-height;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: #fff;
		margin-top: 10rpx;
		padding-left: 10rpx;
		padding-right: 10rpx;
	}

	.confirm-btn-box {
		margin-top: 200rpx;
		width: 100%;
		display: flex;
		justify-content: center;
	}
	.note-box{
		margin-left: 80rpx;
		margin-top: -20rpx;
		text{
			font-size: 24rpx;
			color: steelblue;
			font-weight: 550;
		}
	}
</style>